package com.ailink.concurrent.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by Administrator on 2018/9/26
 */
public class MyReentrantLock {

    private static ReentrantLock lock = new ReentrantLock();

    private static int j = 0;

    public static class ThreadLock implements Runnable  {
        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
//                try {
//                    lock.lock();
//                    System.out.println(Thread.currentThread().getName() + " " + j++);
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                } finally {
//                    lock.unlock();
//                }

                synchronized (this) {
                    System.out.println(Thread.currentThread().getName() + " " + j++);
                    Thread.yield();
                }
            }
        }
    }

    public static void main(String[] args) {
        ThreadLock threadLock = new ThreadLock();
        Thread t1 = new Thread(threadLock, "t1");
        Thread t2 = new Thread(threadLock, "t2");
        t1.start();
        t2.start();
//        try {
//            t1.join();
//            t2.join();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }
}
